var userId = "";
var graphId = "";
var graphVersion;
var wsUri = "";
var websocket = null;

function writeToScreen(message) {
    var output = document.getElementById("output");
    var pre = document.createElement("p");
    pre.style.overflowWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
} 

function doSend(message) {
    writeToScreen("SENT: " + message); 
    websocket.send(message);
} 

function onOpen(evt) {
    writeToScreen("CONNECTED");
    doSend('{"method": "subscribe", "data": {"graph_id": "' + graphId + '", "graph_version": ' + graphVersion + '}}');
} 

function onClose(evt) {
    writeToScreen("DISCONNECTED");
} 

function onMessage(evt) {
    writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>');
    // websocket.close();
} 

function onError(evt) {
    writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data);
} 

function startWebSocket() {
    websocket = new WebSocket(wsUri);

    websocket.onopen = function(evt) {
        onOpen(evt)
    };
    websocket.onclose = function(evt) {
        onClose(evt)
    };
    websocket.onmessage = function(evt) {
        onMessage(evt)
    };
    websocket.onerror = function(evt) {
        onError(evt)
    };
} 

const conversionForm = document.getElementById('agent-form');
const submitButton = document.getElementById('submit');
const spinner = document.getElementById('spinner');

conversionForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    submitButton.disabled = true;
    spinner.classList.remove('d-none');

    const formData = new FormData(conversionForm);
    message = formData.get("message");
    userId = formData.get("user_id");
    graphId = formData.get("graph_id");
    graphVersion = parseInt(formData.get("graph_version"), 10);
    wsUri = formData.get("ws_uri");
    if (wsUri.startsWith("ws://")) {
        wsUri = wsUri + '?user_id=' + userId
        startWebSocket()
    }

    if (message != null) {
        alert("Hello999")
        const response = await fetch('/customized/agent_execution', {
            method: 'POST',
            body: formData,
        });
        const resp = await response.text();
        alert(resp)

        // const graph_exec_id = await response.json();
        // alert(graph_exec_id)
    }
    
    submitButton.disabled = false;
    spinner.classList.add('d-none');
});
